import { mallApi } from '/api/mall';
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { GlobalData } from "/store/state";
import { $event } from "/utils";

Page({
  data: {
    orderId: 0,
    retId: 0 as number,
    orderInfo: {} as any,
    form: {
      name: '' as string,
      phone: '' as string,
      province: '' as string,
      city: '' as string,
      country: '' as string,
      detail: '' as string,
    } as any,
    region: [] as Array<string>,
    canPublish: false,
    publishing: false,
    currencyName: GlobalData.currencyName,
    navigationHeight: GlobalData.navigationHeight,
  },
  onLoad(query: any) {
    $event.on('after:boot', this, () => {
      this.getPostition()
    })
    this.setData({
      orderId: query.orderId,
      retId: query.retId,
    })
    this.getPostition()
  },
  async onShow() {
    const pages = getCurrentPages()
    const orderInfo = pages[pages.length - 2].data.orderInfo
    this.setData({
      orderInfo,
    })
  },
  getPostition() {
    this.setData({
      currencyName: GlobalData.currencyName,
      navigationHeight: GlobalData.navigationHeight,
    })
  },
  inputHandle(e: any) {
    const val = e.detail.value
    const type = e.currentTarget.dataset.type
    this.setData({ [`form.${type}`]: val }, this.canSubmit)
  },
  bindRegionChange: function (e: any) {
    const region = e.detail.value.filter((i: string) => i !== '全部')
    if (region.length < 2) {
      wx.showModal({
        title: '提示',
        content: '请至少选择省市',
        showCancel: false,
      })
      return
    }
    this.setData(
      {
        form: {
          ...this.data.form,
          province: region[0],
          city: region[1],
          country: region[2],
        },
        region,
      },
      () => {
        this.canSubmit()
      },
    )
  },
  chooseAddress() {
    const chooseAddress = () => {
      wx.chooseAddress({
        success: (res) => {
          const form = {
            name: res.userName,
            phone: res.telNumber,
            province: res.provinceName,
            city: res.cityName,
            country: res.countyName,
            detail: res.detailInfo,
          }

          this.setData({ form, region: [res.provinceName, res.cityName, res.countyName] }, this.canSubmit)
        },
      })
    }

    // 获取收货地址授权信息
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.address'] === false) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.address'] === false) {
                wx.showToast({ title: '请允许使用您的收货地址', icon: 'none' })
              } else {
                chooseAddress()
              }
            },
          })
          return
        }
      },
    })
    chooseAddress()
  },
  toDetail(event: WechatMiniprogram.BaseEvent) {
    const data = event.currentTarget.dataset as { id: number; orderId: number }
    wx.navigateTo({ url: `/mall/detail/detail?commodityId=${data.id}&orderId=${data.orderId}` })
  },
  canSubmit() {
    const { form: { name, phone, address }, region } = this.data

    this.setData({
      canPublish: name !== '' && phone !== '' && region.length !== 0 && address !== ''
    })
  },
  async doSubmit() {
    const { publishing, form, retId } = this.data
    if (publishing) return
    try {
      wx.showLoading({ title: '处理中' })
      await mallApi.agreeReturn(retId, form)
      wx.showToast({ title: '提交成功' })
      $event.emit('mallOrderChange')
      setTimeout(() => {
        wx.navigateBack({ delta: 2 })
      }, 1000)
    } catch (error) {
      console.log(error)
      wx.showToast({
        title: `${getMessage(error.data).getMessage() || '发布失败'}`,
        icon: 'none',
      })
      wx.hideLoading()
      this.setData({ publishing: false })
    }
  },
})
